<template >
    <Page class="basic company">
        <template #header>
            <!-- <HousePicker class="mr-2" ref="housePicker" multiple v-model="params.rooms"/> -->
            <EdSelect v-model="params.villageId" ref="selectpatrol" :selectParams="villageNameParams"></EdSelect>
            <!-- <el-input v-model="params.roomCode" placeholder="请输入房间号" /> -->
            <el-input v-model="params.toolName" placeholder="请输入工具名称"/>
            <!-- <el-input v-model="params.toolName" placeholder="请输入工具名称"/> -->
            <EdSelect  :selectParams="statusParams" v-model="params.status"></EdSelect>
            <el-date-picker
                v-model="pickerTime"
                type="daterange"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
            </el-date-picker>
            <el-button class="ed-button ed_black-bottom" @click="search()"><svg-icon class="svg-middle" icon-class="search-svg"/>查询</el-button>
            <el-button class="ed-button ed_white_bottom" @click="reset()" ><svg-icon icon-class="reset-svg"/>重置</el-button>
            <el-button class="ed-button ed_black-bottom ed-button36" style="margin-left:30%" @click="add()"><svg-icon icon-class="add-svg" />新增</el-button>
        </template>
        <ApiTable :api="tableApi" ref="table" :params="params">
            <el-table-column type="index" width="80" label="序号"></el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="villageName" label="所属项目"></el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="toolName" label="工具名称"></el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="toolTotal" label="工具总数"></el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="residualQuantity" label="可借数量"></el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="createTime" label="创建时间"></el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="status" label="状态">
                <template slot-scope="scope">
                    {{scope.row.status == '1' ? '启用' : '停用'}}
                        <el-switch
                            :value="scope.row.status == '1' ? true : false"
                            @change="switchChange(scope.row, scope.row.status == '1' ? '0' : '1')"
                            active-color="#EED096"
                            inactive-color="#909399">
                        </el-switch>
                </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="details" label="简介"></el-table-column>
            <el-table-column :show-overflow-tooltip="true" label="操作" >
                <template slot-scope="scope">
                    <el-button class="ed-table-bottom ed_black_border" @click="toolRentedit(scope.row)" v-has="'property:toolRent:edit'" >编辑</el-button>
                    <el-button class="ed-table-bottom ed_delete_border" @click="del(scope.row)" v-has="'property:toolRent:delete'" >删除</el-button>
                </template>
            </el-table-column>
        </ApiTable>
        <EdDialog ref="dialogRef" v-if="showdialog" :title="isUpdate ? '编辑' : '新增'" @close-dialog="closeDialog" @save-dialog="saveDialog">
            <el-form :model="editForm"  ref="ruleForm" label-position='right' label-width="auto">
                <el-row>
                    <el-col :span="22">
                        <el-form-item label="所属项目" prop="villageId" :rules="$validate.validates({required:true,msg:'请选择'})" >
                            <EdSelect v-model="editForm.villageId" ref="selectpatrol" :selectParams="villageNameParams"  @emit-select-value="projectChange" style="width:100%"></EdSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="工具名称" prop="toolName" :rules="$validate.validates({required:true,msg:'请输入'})" >
                        <el-input v-model="editForm.toolName"></el-input>
                            <!-- <EdSelect filterable v-model="editForm.toolName" ref="selectpatrol" :selectParams="toolNameParams"  style="width:100%"></EdSelect> -->
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="工具总数" prop="toolTotal" :rules="$validate.validates({required:true,msg:'请输入'})" >
                            <el-input v-model="editForm.toolTotal"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="图片" prop="images" :rules="$validate.validates({required:true,msg:'图片不能为空',trigger:['blur','change']})" >
                            <el-upload
                                accept=".jpg, .jpeg, .png, .gif"
                                :action="action"
                                :headers="headers"
                                list-type="picture-card"
                                :limit="3"
                                :multiple="true"
                                :file-list="fileList"
                                :before-upload="beforeImgUpload"
                                :on-preview="handleImgPreview"
                                :on-success="handleImgSuccess"
                                :on-remove="handleImgRemove">
                                <!-- <el-images  v-for="item in editForm.images" :key="item" :src="item" :preview-src-list="editForm.images"></el-images> -->
                                <div >
                                    <i class="el-icon-plus"></i>
                                    <div style="font-size: 14px;color: rgba(0, 0, 0, 0.65); margin: 0 0 8px 0;line-height: 1;margin-top: -50px;">上传图片</div>
                                </div>
                            </el-upload>
                            <el-dialog :visible.sync="dialogVisible" >
                                <img width="100%" :src="dialogImageUrl" alt="">
                            </el-dialog>
                            <p class="labelFont">请上传2M以内的图片，建议上传图片大小430px*430px,至多3张</p>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="简介" prop="details">
                            <!-- <el-input-number v-model="editForm.details"></el-input-number> -->
                            <el-input v-model="editForm.details"></el-input>
                            <!-- <EdSelect v-model="editForm.deviceType" :selectParams="deviceTypeParams" style="width:100%" :formatter="setDeviceType"></EdSelect> -->
                        </el-form-item>
                    </el-col>
                </el-row>  
            </el-form>
        </EdDialog>
        <EdConfirmDelete ref="confirmDeleteRef" @confirmDeleteTrue="confirmDeleteTrue"></EdConfirmDelete>
    </Page>   
    
</template>
<script>
import Page from 'src/views/components/Page.vue';
import PageCard from 'src/views/components/PageCard.vue'
import ApiTable from 'src/components/ApiTable.vue'
import EdSelect from 'src/components/EdSelect.vue'
import HousePicker from 'src/components/HousePicker/index.vue'
import EdDialog from 'src/components/EdDialog.vue';
import {getToken} from 'src/utils/auth'
import EdConfirmDelete from "src/components/EdConfirmDelete.vue";
import {toolManageList,projectList,editTool,addTool,deleteTool,showTool,toolHide,toolShow} from "../api.js"
import { defineComponent } from 'vue'
export default defineComponent({
    name: 'toolRent',
    components: { Page,PageCard, ApiTable, EdSelect,HousePicker,EdConfirmDelete,EdDialog},
    data() {
        return {
            params: {
                rooms: undefined,
                villageId:'',
                villageName:'',
                toolName:'',
                status:'',
                startTime:'',
                endTime:'',
            },
            statusParams:{
                 options: [
                    {label:'启用',value:'1'},
                    {label:'停用',value:'0'}
                 ],
                placeholder:"请选择状态"
            },
            pickerTime: [],
            editForm:{
                villageName:'',
                toolName:'',
                toolTotal:'',
                images:[],
                details:''
            },
            fileList: [],
            action: '',
            headers:{
                RdAuthorization: getToken()
            },
            dialogImageUrl: '',
            isUpdate:false,
            showdialog:false,
            dialogVisible: false,
            villageNameParams:{
                placeholder:"请选择项目",
                options: [],
                props: {label:"villageName", value:"villageId"},
                disabled:false
            },
            confirmRow:''
        }
    },
    created() {

    },
    activated(){
        this.$refs.table.load()
        this.initDic()
        this.action = this.$baseApi + "/file/upload";

    },
    watch:{
        pickerTime: {
            deep: true,
            immediate: true,
            handler(newVal, oldVal) {
                if(newVal && newVal.length > 0) {
                    this.params.startTime = newVal[0]
                    this.params.endTime = newVal[1]
                }
            }
        },
    },
    methods: {
        tableApi:toolManageList,
        search(){
            this.$refs.table.load()
        },
        reset(){
            this.pickerTime=[]
            this.params = {};
            this.$nextTick(()=>{
                this.$refs.table.load(1,10)
            })
        },
        initDic(){
            projectList({page:1,pageSize:999999}).then(response => {
                if(response.success) {
                    let options = response.data.records.map(x=>{return {villageName:x.villageName,villageId:x.villageId}})
                    this.villageNameParams.options=options
                }
            })
        },
        // setDicType(row ,cloumn) {
        //     let options = this.villageNameParams.options.find(x => x.value == row.villageId)
        //     return options.label
        //     },
         // 图片 上传前
        beforeImgUpload(file){
            // console.log('before-->', file)
            const fileType = file.name.split('.');
            const fileDate = fileType.slice(-1);
            if (['jpeg', 'jpg', 'png', 'gif'].indexOf(fileDate[0]) < 0) {
                this.$message.error('仅支持格式：.jpeg、.jpg、.png、.gif!');
                return false
            }
            const isLt5M = file.size / 1024 /1024 < 2;
            if (!isLt5M) {
                return this.$message.error('上传文件大小不能超过 2MB!');
            }
            // return isLt5M;
            return true;
        },
        // 图片 上传成功
        handleImgSuccess(response, file, fileList){
            let res = file.response;
            if(res&&res.success == true){
                // console.log('res',res);
                this.editForm.images.push(res['data'])
            }
        },
        // 图片 删除
        handleImgRemove(file, fileList) {
            this.editForm.images = fileList&&fileList.map(v=>{
                return v['url']
            })
        },
        // 图片 预览
        handleImgPreview(file) {
            console.log('file',file);
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        add(){
            this.showdialog = true
            this.initDic()
        },
        closeDialog(){
            // 用dialog的组件一定要这么写，要不然下次点击的时候不弹框
            this.showdialog = false
            this.$refs.ruleForm.resetFields()
        },
        saveDialog(){
            // this.editForm.villageId = this.$route.query.villageId
            // this.editForm.villageName = this.$route.query.villageName
            // this.editForm.deviceName =this.$refs.selectpatrol.$el.__vue__.selectedLabel
                this.$refs.ruleForm.validate((valid)=>{
                    if(!valid){
                        this.$refs.dialogRef.loading  = false
                        return
                    }
                    // 编辑保存的接口
                    if(this.isUpdate){
                        editTool(this.editForm).then(res=>{
                            if(res.success){
                                this.$message.success({
                                    message: '编辑工具成功！',
                                    duration: 2000,
                                    center:true
                                })
                                this.fileList = []
                                this.$refs['ruleForm'].resetFields()
                                this.$refs.dialogRef.loading  = false
                                this.showdialog = false
                                this.$refs.table.load()
                            }
                        }).catch(res=>{
                            this.$refs.dialogRef.loading  = false
                        })
                    } else {
                        this.villageNameParams.options.forEach((v, i)=>{
                            // console.log('v',v);
                            if(this.editForm.villageId==v.villageId){
                                this.editForm.villageName=v.villageName
                            }
                        })
                        addTool(this.editForm).then(res=>{
                            if(res.success){
                                this.$message.success({
                                    message: '新增工具成功！',
                                    duration: 2000,
                                    center:true
                                })
                                this.showdialog = false
                                this.$refs.table.load()
                                this.$refs.dialogRef.loading  = false
                                this.$refs['ruleForm'].resetFields()
                            }
                        }).catch(res=>{
                            this.$refs.dialogRef.loading  = false
                        })
                    }
                })
        },
        del(row){
            this.confirmRow = row;
            this.$refs.confirmDeleteRef.open("删除确认","确认删除此项数据？","warning")
        },
        confirmDeleteTrue(){
            deleteTool({id: this.confirmRow.id}).then(response => {
                if(response.success == true) {
                    this.$message.success({
                        message: '删除成功！',
                        duration: 2000,
                        center:true
                    });
                    this.$refs.table.load()
                }
            })
        },
        toolRentedit(row){
            this.showdialog = true
            this.isUpdate=true;
            showTool({id: row.id}).then(response => {
                if(response.success == true) {
                    this.editForm = {...response.data}
                    this.editForm.villageId = response.data.villageId.toString()
                    this.editForm.images = response.data.images

                    let fileList = []
                    response.data.images.forEach(x => {
                        fileList.push({url:x})
                    })
                    this.fileList = fileList
                    this.$refs.table.load()
                }
            })
        },
        // 启用禁用状态的切换
        switchChange(row){
            let urlFn = null;
            if(row.status ==1){
                urlFn = toolHide;
            }else {
                urlFn = toolShow
            }
            urlFn({id:row.id}).then(response => {
                    if(response.code == 20000) {
                        this.$message.success({
                            message: row.status === 1 ?  '已切换为禁用' : "已切换为启用",
                            duration: 2000,
                            center:true
                        });
                        this.$refs.table.load()
                    }
                })
        },
        projectChange(row){
            // console.log('row',row);
            let options = this.villageNameParams.options.find(x=>{
                return x.villageId == row
            })
            this.editForm.villageName = options.villageName
        }
    }

})
</script>
<style lang="scss">

</style>